<template>
  <div class="singer">
      <list-view :singers="singers" @singerDetailSelected="handleSelected" ref="list"></list-view>
      <transition name="slide">
        <router-view></router-view>
      </transition>
  </div>
</template>
<script>
import { getSingerList } from 'api/singer'
import { ERR_OK } from 'api/config'
import Singer from 'common/js/singer'
import ListView from 'base/listview/listview'
import {mapMutations} from 'vuex'
import {playlistMixin} from 'common/js/mixin'
const HOT_NAME = '热门'
const HOT_SINGER_LEN = 10
export default {
  name: 'Singer',
  mixins: [playlistMixin],
  data () {
    return {
      singers: []
    }
  },
  created () {
    this._getSingerList()
  },
  methods: {
    handlePlaylist (playlist) {
      const bottom = playlist.length > 0 ? '120px' : ''
      this.$refs.list.$el.style.bottom = bottom
      this.$refs.list.refresh()
    },
    handleSelected (singer) {
      this.$router.push({path: `/singer/${singer.id}`})
      this.setSinger(singer)
    },
    ...mapMutations({setSinger: 'SET_SINGER'}),
    _getSingerList () {
      getSingerList()
        .then(res => {
          if (res.code === ERR_OK) {
            this.singers = this._normalizeSinger(res.data.list)
          }
        })
        .catch(e => {
          console.log(e)
        })
    },
    _normalizeSinger (list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      }
      list.forEach((item, index) => {
        if (index < HOT_SINGER_LEN) {
          map.hot.items.push(new Singer({
            name: item.Fsinger_name,
            id: item.Fsinger_mid
          }))
        }

        let key = item.Findex
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          }
        }
        map[key].items.push(new Singer({
          name: item.Fsinger_name,
          id: item.Fsinger_mid
        }))
      })

      let hot = []
      let normal = []
      for (let key in map) {
        let val = map[key]
        if (val.title.match(/[A-z]/)) {
          normal.push(val)
        } else if (val.title === HOT_NAME) {
          hot.push(val)
        }
      }
      normal.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0)
      })
      return hot.concat(normal)
    }
  },
  components: {
    ListView
  }
}
</script>
<style lang="scss" scoped>
.slide-enter-active,.slide-leave-active{
  transition: all 0.3s;
}
.slide-enter,.slide-leave-to{
  transform: translateX(100%);
}
</style>
